package com.android.flickr;

import java.net.URL;
import java.security.MessageDigest;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;


public class FlickrToknHandlr {
	public String method,api_key, secret,numbtok,token,api_sig, mt,fulltoken;
	public FlickrToknHandlr(String minitoken)
	{
		/*Initializes class. Sets value to variables needed for connection*/
		method = "methodflickr.auth.getFullToken";
		api_key = "api_keyd35a91cf46cbfc48c5dec2507c0c2821";
		secret = "d0d11ca8e6bb28b5";
		token = "mini_token"+minitoken;
		mt = minitoken;
		fulltoken = null;
	}
	public String getFullToken()
	{
		try {
			String s = secret+api_key+method+token;
			MessageDigest md= MessageDigest.getInstance("MD5");
			md.update(s.getBytes(),0,s.length());
			System.out.println("getFullToken");
//			md.h
			byte[] byteSig = md.digest();
			
			StringBuffer hexString = new StringBuffer();
			for (int i=0;i<byteSig.length;i++) {
				String hex = Integer.toHexString(0xFF & byteSig[i]);
				if (hex.length() == 1) {
				    // could use a for loop, but we're only dealing with a single byte
				    hexString.append('0');
				}
				hexString.append(hex);

			}
			System.out.println("Hex String.... NICE!!! --> hexString: "+hexString);
			api_sig = hexString.toString();
			System.out.println("http://flickr.com/services/rest/?method=flickr.auth.getFullToken&api_key=d35a91cf46cbfc48c5dec2507c0c2821&mini_token="+mt+"&api_sig="+api_sig);
			URL url = new URL("http://flickr.com/services/rest/?method=flickr.auth.getFullToken&api_key=d35a91cf46cbfc48c5dec2507c0c2821&mini_token="+mt+"&api_sig="+api_sig);
			System.out.println("GO GO POWER RANGERS!");
			SAXParserFactory spf = SAXParserFactory.newInstance();
			System.out.println("Wooduardo");
			SAXParser sp = spf.newSAXParser();
			System.out.println("Email Look at this");
			XMLReader xr = sp.getXMLReader();
			System.out.println("Project Computer as Green");
			TokenParser tp = new TokenParser();
			System.out.println("Nasty");
			xr.setContentHandler(tp);
			System.out.println("Oh Yeah?");
			xr.parse(new InputSource(url.openStream()));
			System.out.println("We Don't know!");
			fulltoken = tp.getToken();
			System.out.println("FULLTOKEN: "+fulltoken);

		}
		
		catch (Exception e) {
			System.out.println("ERROR: Something is effed");
		}
		return fulltoken;
	}
	

}
